package com.clearliang.alarmnotice.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import static android.content.Context.ALARM_SERVICE;

/**
 * Created by ClearLiang on 2019/2/27
 * <p>
 * Function :
 */
public class AlarmUtil {
    private AlarmManager am;
    private PendingIntent pi;

    public void setAlarmTime(Context context, long triggerAtMillis, int id, boolean isAgain) {
        am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        Intent intent1 = new Intent("android.alarm.demo.action");
        Bundle bundle = new Bundle();
        bundle.putLong("triggerAtMillis",triggerAtMillis);
        bundle.putInt("id",id);
        bundle.putBoolean("isAgain",isAgain);
        intent1.putExtras(bundle);
        pi = PendingIntent.getBroadcast(context, id, intent1, PendingIntent.FLAG_CANCEL_CURRENT);

        //闹铃间隔， 这里设为1天闹一次，在第2步我们将每隔1分钟收到一次广播
        //long interval = AlarmManager.INTERVAL_DAY;
        long interval = 60 * 1000;
        long time = System.currentTimeMillis() + triggerAtMillis;
        //LogUtils.e("时间：", System.currentTimeMillis(), triggerAtMillis, time);
        //am1.setRepeating(AlarmManager.RTC_WAKEUP, time, interval, sender);

        if (Build.VERSION.SDK_INT < 19) {
            am.set(AlarmManager.RTC_WAKEUP, time, pi);
            //am.setRepeating(AlarmManager.RTC_WAKEUP, time, interval, pi);
        } else {
            am.setExact(AlarmManager.RTC_WAKEUP, time, pi);
            //m.setRepeating(AlarmManager.RTC_WAKEUP, time, interval, pi);
        }
    }

    public void stopAlarmTime(){
        am.cancel(pi);
    }
}
